<template>
  <div style="margin-top: 20px">
    <ko-card :title="$t('business.network.default_backend')">
      <el-form-item ref="form" label-position="top" :model="defaultBackend">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('business.network.target') + 'Service'">
              <el-select
                v-model="serviceName"
                style="width: 100%"
                @change="onServiceChange(serviceName)"
              >
                <el-option
                  v-for="service in services"
                  :key="service.metadata.name"
                  :label="service.metadata.name"
                  :value="service.metadata.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('business.network.port')">
              <el-select v-model="servicePort">
                <el-option
                  v-for="port in servicePorts"
                  :key="port.name"
                  :label="port.port"
                  :value="port.port"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
    </ko-card>
  </div>
</template>

<script setup lang="ts">
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
// import { listServicesWithNs } from "@/api/services";
import { computed, onMounted, ref, watch } from "vue";
import { getObjectFromKey, setObjectFromKey } from "../../../utils";
import { Service, useK8SApi } from "../../../api/k8s";

const { serviceRepo } = useK8SApi();

type Prop = {
  namespace?: string;
  cluster?: string;
  defaultBackendObj?: object;
  newVersion?: boolean;
};

const props = withDefaults(defineProps<Prop>(), { newVersion: true });
const emit = defineEmits(["update:defaultBackendObj"]);

const defaultBackend = ref<any>({ service: {} });
const services = ref<Service[]>([]);
const servicePorts = ref([]);
const servicePath = ref("");
const portPath = ref("");
const serviceName = computed({
  get() {
    return getObjectFromKey(defaultBackend.value, serviceNamePath.value);
  },
  set(value) {
    setObjectFromKey(defaultBackend.value, serviceNamePath.value, value);
  }
});
const servicePort = computed({
  get() {
    return getObjectFromKey(defaultBackend.value, servicePortPath.value);
  },
  set(value) {
    setObjectFromKey(defaultBackend.value, servicePortPath.value, value);
  }
});

const onServiceChange = serviceName => {
  const svr = services.value.find(svr => svr.metadata.name === serviceName);
  if (svr) {
    servicePorts.value = svr.spec.ports;
  }
};

const serviceNamePath = computed(() => {
  const nestedPath = "service.name";
  const flatPath = "serviceName";
  return props.newVersion ? nestedPath : flatPath;
});

const servicePortPath = computed(() => {
  const nestedPath = "service.port.number";
  const flatPath = "servicePort";
  return props.newVersion ? nestedPath : flatPath;
});

const getDefaultBackend = computed(() => {
  const backend = {};
  setObjectFromKey(backend, servicePath.value, "");
  setObjectFromKey(backend, portPath.value, 0);
  return backend;
});

const getServices = () => {
  serviceRepo
    .getService({
      namespace: props.namespace,
      clusterName: props.cluster
    })
    .then(res => {
      services.value = res?.items ?? [];
    });
};

watch(
  () => props.namespace,
  (old, newValue) => {
    if (old !== newValue) {
      setObjectFromKey(defaultBackend.value, servicePath.value, "");
      setObjectFromKey(defaultBackend.value, portPath.value, 0);
      getServices();
    }
  }
);

onMounted(() => {
  servicePath.value = serviceNamePath.value;
  portPath.value = servicePortPath.value;
  defaultBackend.value = props.defaultBackendObj ?? getDefaultBackend.value;
  emit("update:defaultBackendObj", defaultBackend.value);

  getServices();
});
</script>

<style scoped></style>
